package person.zjh.kaoyansharehub.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import person.zjh.kaoyansharehub.dto.UserLoginDTO;
import person.zjh.kaoyansharehub.dto.UserRegisterDTO;
import person.zjh.kaoyansharehub.mapper.UserMapper;
import person.zjh.kaoyansharehub.pojo.User;
import person.zjh.kaoyansharehub.result.Result;
import person.zjh.kaoyansharehub.service.UserService;
import person.zjh.kaoyansharehub.utils.JwtUtil;
import person.zjh.kaoyansharehub.utils.RandomGenerator;

import java.util.HashMap;

/**
 * @description: TODO
 * @author 郑佳豪
 * @date 2025/2/12 11:25
 * @version 1.0
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;
    private final HttpSession session;




    @Override
    public Result userLogin(UserLoginDTO requestParam) {

        String verCode = (String) session.getAttribute("verCode");
        if (!verCode.equalsIgnoreCase(requestParam.getVerificationCode())) {
            return Result.error("验证码不正确");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("user_account", requestParam.getUserAccount());
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            return Result.error("账号不存在");
        }
        if(!requestParam.getUserPassword().equals(user.getPassword())){
            return Result.error("密码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId",user.getUserId());
        map.put("userName",user.getUserName());
        map.put("userAccount",user.getUserAccount());
        map.put("userAvatar",user.getAvatar());
        map.put("userEmail",user.getEmail());
        String token = JwtUtil.generateJwt(map);
        return Result.success(token);
    }

    @Override
    public void userRegister(UserRegisterDTO requestParam) {
        String account = RandomGenerator.generatorAccount(9);
        while (userIsExist(account)){
            account =  RandomGenerator.generatorAccount(9);
        }
        User user = User.builder()
                .userAccount(account)
                .userName(requestParam.getUserName())
                .password(requestParam.getPassword())
                .email(requestParam.getEmail())
                .build();
        baseMapper.insert(user);
    }

    /**
     * 校验用户是否存在
     * @param account 账号
     * @return 存在true  不存在false
     */
    public boolean userIsExist(String account){
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>()
                .eq("user_account", account);
        User user = userMapper.selectOne(queryWrapper);
        return user != null;
    }




}
